

[Bindable]private var _xlcCatalog:XMLListCollection;      //the dataProvider for the datagrid
            
private var _lastIndex:int = 0;

// Result handler - gets called after xml is loaded.
private function personXmlResultHandler(event:ResultEvent):void
{
    var xmlCatalog:XML = XML(event.result);
    _xlcCatalog = new XMLListCollection(xmlCatalog.collection.Person);
    
    PersonGrid.selectedIndex = _lastIndex;
    selectPerson();
}

private function addPerson():void
{
    var defaultText:String = "<nieuw>";
    personService.url = WEBROOT + "/flex/person/addperson.rails?name=" + defaultText;
    _lastIndex = _xlcCatalog.length;
    personService.send();
    
    NameInput.text = defaultText;
    NameInput.setFocus();                
    
}

private function deletePerson():void
{                 
    personService.url = WEBROOT + "/flex/person/deleteperson.rails?id=" + PersonGrid.selectedItem.Id;
    personService.send();
}

private function selectPerson():void
{
    NameInput.text = PersonGrid.selectedItem.Name;
    var url:String = PersonGrid.selectedItem.PhotoUrl
    
    if (!url)
    {
      url = WEBROOT + "/content/images/sleeping.jpg";
    }
    PersonImage.source = url;
    _lastIndex = PersonGrid.selectedIndex;
}

private function updatePerson():void
{
    PersonGrid.selectedItem.Name = NameInput.text;
    PersonGrid.selectedItem.PhotoUrl = PersonImage.source;
    
    var obj:Object = new Object();

    obj['id'] = PersonGrid.selectedItem.Id;
    obj['xml_data'] = PersonGrid.selectedItem.valueOf();

    personService.url = WEBROOT + "/flex/person/updateperson.rails";
    personService.method = "POST";               
    
    personService.send(obj);
}   

private function selectNameInputText():void
{
    NameInput.selectionBeginIndex = 0;
    NameInput.selectionEndIndex = NameInput.length;
}


private function showWindow(title:String, modal:Boolean):void
{
    var inputWindow:InputWindow = new InputWindow();
    inputWindow.title = title;
    
    inputWindow.addEventListener("input", inputHandler);
    PopUpManager.addPopUp(inputWindow, this, modal);
    PopUpManager.centerPopUp(inputWindow);
    
    if (PersonGrid.selectedItem)
    {
      inputWindow.setInput(PersonGrid.selectedItem.PhotoUrl);
    }
}

public function inputHandler(event:InputEvent):void
{
    PersonImage.source = event.inputText;
    updatePerson();
}